package com.apex.crm.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.Base64;

/**
 * @author XiaoYang
 * @version 1.0
 * @program: crm
 * @Classname UserIDBase64
 * @description TODO
 * @date 2021/4/21 14:09
 */

public class UserIDBase64 {

    //userID解密
    public static Integer decoderUserID(String encodedUserID){
        if(StringUtils.isBlank(encodedUserID)){
            return null;
        }
        try{
            String reversedString = new StringBuffer(encodedUserID).reverse().toString();
            String base64String = reversedString.replaceAll("#","=");
            int userIDPos = base64String.indexOf("==")+6;
            String realBase64UserID = base64String.substring(userIDPos);
            String base64Encoded = new String(Base64.getDecoder().decode(realBase64UserID.getBytes()));
            return Integer.parseInt(base64Encoded);
        }catch (Exception e){
            return null;
        }
    }

    //userID加密
    public static String encoderUserID(Integer userID){
        String base64UserIDEncoded = Base64.getEncoder().encodeToString((userID+"").getBytes());
        String currentStringBase64Encoded = Base64.getEncoder().encodeToString((System.currentTimeMillis()+"").getBytes());
        String keyString = currentStringBase64Encoded+currentStringBase64Encoded.substring(4,8)+base64UserIDEncoded;
        byte[] codeBytes = keyString.getBytes();
        byte[] orderBytes = new byte[codeBytes.length];
        for(int i=0;i<codeBytes.length;i++){
            orderBytes[i]=codeBytes[codeBytes.length-i-1];
        }
        return new String(orderBytes).replaceAll("=","#");
    }

}
